#!/usr/bin/php
<?php
$iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( getcwd( ) ) );

if( count( $argv ) == 1 ) {
	showUsage( );
	exit;
}

$script = array_shift( $argv );

$command = 'c_' . array_shift( $argv );

if( function_exists( $command ) ) {
	$command( $argv );
	exit;
}


function showUsage( ) {
	echo "Usage: sphoof [command]\n";
}

function c_findclasses( $arguments ) {
	$classes = array( );
	$iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( getcwd( ) ) );
	foreach( $iterator as $file ) {
		if ( preg_match('/\.svn/', $file ) ) {
			continue;
		}
		if( $file->isFile( ) ) {
			foreach( getClasses( (string) $file ) as $classname ) {
				$classes[$classname] = substr( (string) $file, (int) ( strlen( getcwd( ) ) + 1 ) );
			}
		}
	}

	// we now know all classes, time for output.
	if( count( $classes ) && ksort( $classes ) ) {
		echo "<?php\nreturn array(\n";
		foreach( $classes as $classname => $filename ) {
			echo "\t'$classname' => '$filename',\n";
		}
		echo ");\n";
	}
}

/**
 * Finds all classes in a file.
 *
 * @param string $filename
 * @return array
 * @author Richard van Velzen
 */
function getClasses( $filename ) { 
	$classes = array( ); 

	$tokens = token_get_all( file_get_contents( $filename ) ); 

	for( $i = 0, $length = count( $tokens ); $i !== $length; ++$i ) { 
		if( is_array( $tokens[$i] ) && ( T_CLASS === $tokens[$i][0] || T_INTERFACE === $tokens[$i][0] ) ) { 
			for( $j = $i + 1; $j !== $length; ++$j ) { 
				if( is_array( $tokens[$j] ) ) { 
					if( T_STRING == $tokens[$j][0] ) {
						$classes[] = $tokens[$j][1]; 
						continue 2; 
					}
					elseif( T_WHITESPACE == $tokens[$j][0] || T_COMMENT == $tokens[$j][0] || T_DOC_COMMENT == $tokens[$j][0] ) { 
						continue;
					}
				}
			} 
		} 
	} 
	return $classes; 
}
